const https = require('https');
const config = require('../config');
const stringRandom = require('string-random');//生成随机字符串
const moment = require('moment');
const crypto = require('crypto');

let gzh = {
    /**
     * 根据code获取openid和access_token（网页授权access_token与普通access_token不同）
     * @param code
     * @returns {Promise}
     */
    getToken: (code) => {
        return new Promise((resolve, reject) => {
            let url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code';
            url = url.replace('APPID', config.appid).replace('CODE', code).replace('SECRET', config.appsecret);
            https.get(url, clientRes => {
                let reqData = '';
                clientRes.on('data', (data) => {
                    reqData += data;
                });
                clientRes.on('end', () => {
                    reqData = JSON.parse(reqData);
                    resolve(reqData);
                })
            })
        })
    },

    /**
     * 根据openid和access_token获取用户信息
     * @param openid
     * @param access_token
     * @returns {Promise}
     */
    getUserInfo: (openid, access_token) => {
        return new Promise((resolve, reject) => {
            let url = 'https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN';
            url = url.replace('ACCESS_TOKEN', access_token).replace('OPENID', openid);
            https.get(url, clientRes => {
                let reqData = '';
                clientRes.on('data', (data) => {
                    reqData += data;
                });
                clientRes.on('end', () => {
                    reqData = JSON.parse(reqData);
                    resolve(reqData);
                })
            })
        })
    },

    /**
     * 获取基础access_token（普通access_token）用于全局接口调用凭证
     */
    getBaseToken: () => {
        return new Promise((resolve, reject) => {
            let url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET';
            url = url.replace('APPID', config.appid).replace('APPSECRET', config.appsecret);
            https.get(url, clientRes => {
                let reqData = '';
                clientRes.on('data', (data) => {
                    reqData += data;
                });
                clientRes.on('end', () => {
                    reqData = JSON.parse(reqData);
                    resolve(reqData);
                })
            })
        })
    },

    /**
     * 根据access_token获取access_ticket
     * @param access_token
     * @returns {Promise}
     */
    getTicket: (access_token) => {
        return new Promise((resolve, reject) => {
            let url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi';
            url = url.replace('ACCESS_TOKEN', access_token);
            https.get(url, clientRes => {
                let reqData = '';
                clientRes.on('data', (data) => {
                    reqData += data;
                });
                clientRes.on('end', () => {
                    reqData = JSON.parse(reqData);
                    resolve(reqData);
                })
            })
        })
    },

    /**
     * 根据ticket获取签名
     * @param ticket
     * @returns {Promise}
     */
    getSignature: (ticket, paramUrl) => {
        return new Promise((resolve, reject) => {
            try {
                let submitData = {
                    noncestr: stringRandom(16),
                    timestamp: moment(new Date()).format("YYYYMMDDHHmm"),
                    url: paramUrl,
                    jsapi_ticket: ticket
                };
                let resultStr = '';//拼接后的字符串
                //进行字典排序
                let sortData = Object.keys(submitData).sort();
                for (let key in sortData) {
                    resultStr += sortData[key] + '=' + submitData[sortData[key]] + '&';
                }
                resultStr = resultStr.substr(0, resultStr.length - 1);
                let sha1 = crypto.createHash('sha1');
                sha1.update(resultStr);
                let signature = sha1.digest('hex');
                submitData.signature = signature;
                resolve(submitData);
            } catch (e) {
                reject(e);
            }
        })
    }
};
module.exports = gzh;